/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Space,
  Table,
  Form,
  Spin,
  Button,
  Select,
  Modal,
  // Popconfirm,
  message,
  Tag,
  TreeSelect,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import css from './index.less';
import { getList, doAssign, getAssign, menuList } from './api';
import { stateColors } from '@/utils/variable';
import { PlusOutlined } from '@ant-design/icons';
import AddForm from './AddForm';
import EditForm from './EditForm';
import { debounce } from 'lodash';
import MyInput from '@/components/MyInput';

/**
 * 系统管理/权限管理/角色管理
 */
const SuperTable: React.FC<{
  dataSource: RoleAPI.DataType[];
  pagination: any;
  infoUpdate: any;
  menus: any;
}> = ({ dataSource, pagination, infoUpdate, menus }) => {
  const [form] = Form.useForm();
  const editRef = useRef<any>(false);
  const { SHOW_PARENT } = TreeSelect;
  const [perModal, setPerModal] = useState(false);
  const [perModalData, setPerModalData] = useState<RoleAPI.DataType>();
  //spin可见性
  const [spinning, setSpinning] = useState(false);
  // 校验
  const rules = [{ required: true, message: '不能为空' }];

  //分配权限
  const perHandle = async (record: RoleAPI.DataType) => {
    setPerModalData(record);
    setPerModal(true);
  };

  useEffect(() => {
    if (perModalData?.id) {
      getAssignList(perModalData.id);
    }
  }, [perModal]);

  // 根据角色获取菜单
  async function getAssignList(id: string) {
    const res = await getAssign(id);

    if (res.code === 200) {
      const data: never[] = [];
      getPerData(res.data, data);
      form.setFieldValue('permissionIds', data);
    } else {
      message.error(res.msg);
    }

    function getPerData(pers: any, resData: any) {
      pers.forEach((item: any) => {
        resData.push(item.id);
        if (item.permissions && item.permissions.length) getPerData(item.permissions, resData);
      });
    }
  }

  // 取消分配权限
  const onCancel = () => {
    setPerModalData(undefined);
    setPerModal(false);
  };

  // 确认分配权限
  const onFinish = () => {
    form.validateFields().then(async (values) => {
      setSpinning(true);
      values.roleId = perModalData?.id;
      const res = await doAssign(values);
      if (res.code === 200) {
        infoUpdate(true);
        message.success(res.msg);
        onCancel();
      } else {
        message.error(res.msg);
      }
      setSpinning(false);
    });
  };

  //编辑
  const updateHandle = async (record: RoleAPI.DataType) => {
    editRef.current.setEditData(record);
    editRef.current.setVis({ open: true, id: record.id });
  };

  //删除
  // const deleteHandle = async (record: RoleAPI.DataType) => {
  //   if (record.id) {
  //     const id = record.id;
  //     const res = await del(id);
  //     if (res.code === 200) {
  //       message.success(res.msg);
  //       infoUpdate(true);
  //     } else {
  //       message.error('删除失败');
  //     }
  //   }
  // };

  const columns: ColumnsType<RoleAPI.DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      ellipsis: true,
      width: 50,
      render: (text, record, index) =>
        `${(pagination.current - 1) * pagination.pageSize + (index + 1)}`,
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      ellipsis: true,
      width: 100,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      align: 'center',
      ellipsis: true,
      width: 150,
    },
    {
      title: '创建人',
      dataIndex: 'creatorName',
      key: 'creatorName',
      align: 'center',
      ellipsis: true,
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      ellipsis: true,
      width: 80,
      render: (value: string) => {
        return (
          <>
            {value === '禁用' ? (
              <Tag color={stateColors[0]}>禁用</Tag>
            ) : (
              <Tag color={stateColors[1]}>启用</Tag>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      ellipsis: true,
      fixed: 'right',
      width: 150,
      render: (_, record) => {
        return (
          <Space size="middle">
            <a onClick={() => perHandle(record)}>分配权限</a>
            <a onClick={() => updateHandle(record)}>编辑</a>
            {/* <Popconfirm
              title="是否删除此角色？"
              onConfirm={() => deleteHandle(record)}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm> */}
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <Table
        bordered
        columns={columns}
        dataSource={dataSource}
        pagination={pagination}
        scroll={{ x: 1000 }}
        rowKey="id"
      />

      <EditForm ref={editRef} getAll={infoUpdate} />

      <Modal
        title="分配权限"
        width={570}
        open={perModal}
        onOk={onFinish}
        onCancel={onCancel}
        destroyOnClose
        maskClosable={false}
        closable={false}
      >
        <Spin spinning={spinning}>
          <Form form={form} preserve={false}>
            <Form.Item label="权限" name="permissionIds" rules={rules}>
              <TreeSelect
                treeData={menus}
                placeholder="请选择权限"
                treeCheckable
                showCheckedStrategy={SHOW_PARENT}
              />
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </>
  );
};

const Index: React.FC = () => {
  const [tableData, setTableData] = useState<RoleAPI.DataType[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [current, setCurrent] = useState<number>(1);
  const [page, setPage] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [roleName, setRoleName] = useState<string>('');
  const [status, setStatus] = useState<number>();
  const addRef = useRef<any>(false);
  //菜单列表数据
  const [menus, setMenus] = useState([]);

  // 新增
  const add = () => {
    addRef.current.setVis(true);
  };

  const getAll = async () => {
    const condition: RoleAPI.ConditionQuery = {
      page: current,
      pageSize: page,
      roleName: roleName,
      status: status,
    };
    setLoading(true);
    const res = await getList(condition);
    if (res.code === 200) {
      setTotal(res.data.count);
      setTableData(res.data.list);
      setLoading(false);
    } else {
      message.error(res.msg);
      setLoading(false);
    }
  };

  // 获取菜单列表
  const getMenuList = async () => {
    const res = await menuList();

    if (res.code === 200) {
      setMenus(transfromData(res.data));
    } else {
      message.error(res.msg);
    }

    function transfromData(data: any) {
      return data.map((item: any) => {
        const { name, id, permissions: children } = item;
        const resData = { title: name, value: id, key: id, children: children };
        if (children && children.length) {
          resData.children = transfromData(children);
        }
        return resData;
      });
    }
  };

  const pagination = {
    current: current,
    pageSize: page,
    total: total,
    showTotal: () => `共 ${total} 条数据`,
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: (cur: number, p: number) => {
      setCurrent(cur);
      setPage(p);
    },
  };

  useEffect(() => {
    getAll();
  }, [current, page, roleName, status]);

  useEffect(() => {
    getMenuList();
  }, []);

  const changeStatus = (values: number) => {
    setStatus(values);
    setCurrent(1);
  };

  // 搜索操作进行防抖处理
  const onSearchInfo = useCallback(
    debounce((values: string) => {
      setRoleName(values.trim());
      setCurrent(1);
    }, 500),
    [],
  );

  return (
    <>
      <div className={css.form}>
        <Form name="basic" layout="inline" autoComplete="off">
          <Form.Item label="角色状态" name="status">
            <Select
              allowClear
              placeholder="请选择角色状态"
              style={{ width: 150 }}
              options={[
                { value: 1, label: '启用' },
                { value: 0, label: '禁用' },
              ]}
              onChange={changeStatus}
            />
          </Form.Item>

          <Form.Item label="角色名称" name="roleName">
            <MyInput
              allowClear
              placeholder="请输入角色名称"
              onChange={(e: any) => {
                onSearchInfo((e.target as HTMLInputElement).value);
              }}
            />
          </Form.Item>
        </Form>
        <Button type="primary" onClick={add}>
          <PlusOutlined /> 新增
        </Button>
      </div>
      <Spin spinning={loading}>
        <SuperTable
          dataSource={tableData}
          pagination={pagination}
          infoUpdate={getAll}
          menus={menus}
        />
      </Spin>

      <AddForm ref={addRef} menus={menus} getAll={getAll} />
    </>
  );
};

export default Index;
